/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.utils;

public class ThreadRoom {
	final static public int INFINITE=0;

	private int number_of_users=0;
	private boolean locked=false;
	private int in_room=0;

	public ThreadRoom(int number_of_users){
		this.number_of_users=number_of_users;
	}

	public void enter(){
		synchronized (this){
			while (locked || !(number_of_users==0 || in_room<number_of_users)){
				try {
					Thread.sleep(10);
				} catch (Exception whocares){
				}
			}
			in_room++;
		}
	}

	public synchronized void exit(){
		in_room--;
	}

	public void lock(){
		synchronized (this){
			if (locked){
				Log.critical.out("ThreadRoom","A double lock was found");
			}
			locked=true;
			while (number_of_users>0){
				try {
					Thread.sleep(10);
				} catch (Exception whocares){
				}
			}
		}
	}

	public void unlock(){
		if (!locked){
			Log.critical.out("ThreadRoom","A double unlock was found");
		}
		locked=false;
	}
}

